import { QuestDefaultApi } from '@/library/util/api';
import { defaultErrorHandler } from '@/library/util/error-handler';
import { TOKEN } from '@/library/util/tokens';
import { User } from '@/model/login/User';
import router from '@/router';
import { routeInfo } from '@/router/info';
import { LOGIN } from '@/router/route-name';
import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';

interface LoginInforState {
  /** 用户信息 */
  userInfo: User;

  /** 登陆状态 */
  loginState: boolean | null;

  /** token */
  token: string;

  /** 基础信息 */
  isLoading: boolean;
}

export const useLoginInforStore = defineStore({
  id: 'LoginInforStore',
  state: (): LoginInforState => ({
    userInfo: new User(),
    loginState: null,
    token: '',
    isLoading: false,
  }),
  getters: {
    getUserInfo(): User {
      return this.userInfo;
    },
  },
  actions: {
    /**
     * 设置用户信息
     * @param userInfo 用户信息
     */
    setUserInfo(userInfo: User): void {
      window.localStorage.setItem('userInfo', JSON.stringify(userInfo));
      this.userInfo = userInfo;
    },

    /**
     * 设置登录状态
     * @param state 登录状态
     */
    setLoginState(state: boolean) {
      this.loginState = state;
      routeInfo.setLoginState(state);
    },

    /**
     * 设置token
     * @param token token
     */
    setToken(token: string) {
      this.token = token;
      window.localStorage.setItem(TOKEN, token);
    },

    /**
     * 初始化
     * @returns
     */
    async Initialize() {
      const route = router.currentRoute.value;
      // 进入login将登陆状态置为false
      if (route.fullPath === '/login') {
        this.setLoginState(false);
        return;
      }

      // 检查登录信息
      let result: User;

      try {
        result = await QuestDefaultApi.loginStatusGet();
      } catch (error) {
        defaultErrorHandler(error);
        this.setToken('');
        this.setLoginState(false);
        return;
      }

      this.OnLogin(result);
    },

    /**
     * 登录时操作
     */
    OnLogin(result: User) {
      if (!result) {
        // throw new Error('result 为空');
        this.setLoginState(false);
        return;
      }

      this.setUserInfo(result);
      this.setLoginState(true);
    },

    /**
     * 登出时操作
     */
    OnLoginOut() {
      this.setToken('');
      this.setUserInfo(new User());
      this.setLoginState(false);

      router.push({ name: LOGIN });
    },

    /**
     *
     * @returns 用户没有登陆
     */
    NotLogin() {
      if (this.loginState === null) {
        return;
      }
      this.LoginOut();
    },

    /**
     * 登出操作
     */
    async LoginOut() {
      try {
        await QuestDefaultApi.logoutPost();
        this.OnLoginOut();
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    /**
     * 注册用户
     * @param userName
     * @param password
     * @param phoneNum
     */
    async Register(userName: string, password: string, phoneNum?: string) {
      const params = {
        nickName: userName,
        userName: userName,
        password: password,
      };
      try {
        if (password !== phoneNum) {
          throw new Error('密码与确认密码不同');
        }
        const result = await QuestDefaultApi.userRegistPost(params, {
          headers: { token: '' },
        });
        // console.log(result);
        if (result) {
          message.success('用户创建成功');
        }
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    /**
     * 通过用户名和密码登录
     * @param userName
     * @param password
     */
    async LoginByPassword(userName: string, password: string) {
      const params = {
        userName: userName,
        password: password,
      };
      try {
        const result = await QuestDefaultApi.loginPost(params, {
          headers: { token: '' },
        });
        this.setToken(result.token);
        this.OnLogin(result.userInfo);

        router.replace('/manage');
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    /**
     * 获取用户信息
     */
    async GetUserInfor() {
      try {
        // const result = await QuestDefaultApi.
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    /**
     * 假登录
     */
    fakeLogin() {
      this.setLoginState(true);
      router.replace('/manage');
    },

    setAvatar(value: string) {
      this.userInfo.avatar = value;
    },

    /**
     * 请求用户信息
     */
    async queryInfo() {
      try {
        this.isLoading = true;

        const result = await QuestDefaultApi.userUserInfoGet({
          userId: this.userInfo.userId,
        });

        if (result) {
          this.userInfo = result;
          this.userInfo.password = '';
        }
      } catch (error) {
        defaultErrorHandler(error);
      } finally {
        this.isLoading = false;
      }
    },
  },
});
